package com.cb.domain.service.file;

import java.awt.Image;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.swing.ImageIcon;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cb.common.util.ConfigUtil;


/**
 * 
 * 图片上传
 * @author sdm
 *
 */
public class ImageFileUpload extends AbstractFileUpload {
	
	private HttpServletRequest request=null;
	/**
	 * 保存上传的文件名列表
	 */
	private String[]fileNames=null;
	/**
	 * 保存上传的文件服务器路径列表
	 */
	private	String[]filePaths=null;
	/**
	 * 保存表单file元素name值
	 */
	private	String[]fileFormName=null;
	/**
	 * 保存路径MAP
	 */
	private HashMap<String, String> filePathMap=new HashMap<String, String>();
	
	private Map<String, MultipartFile> fileSet=new HashMap<String, MultipartFile>();

	public ImageFileUpload(HttpServletRequest request,Integer fileType) {
		setFileSizeLimited(8*1024*1024l*100);
		setFileType(fileType);
		//设置为图片上传
		setFileExtAllowed(ALLOWED_FILE_EXT_IMAGE);
		this.request=request;
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
		
	    for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {   
	        String key = (String)it.next();   
	        MultipartFile file = multipartRequest.getFile(key);
	        if (file.getOriginalFilename().length() > 0) {   
	        	fileSet.put(key, file);   
	        	this.fileSize=(Long[])ArrayUtils.add(fileSize, file.getSize());
	        }   
	    } 
	}
	public Boolean checkFiles(Integer width,Integer height){
		//若没有上传文件，则返回
		if(fileSet.size()==0) return false;
		Boolean flag=true;
		for(String fileKey:fileSet.keySet()){
			MultipartFile file = fileSet.get(fileKey);
			try{
			    	Image inImage = new ImageIcon(file.getBytes()).getImage();
			    	
			    	Integer srcWidth = (int) inImage.getWidth(null);
			    	Integer srcHeight = (int) inImage.getHeight(null);
					if(!width.equals(srcWidth)){
						flag=false;
					}
					if(!height.equals(srcHeight)){
						flag=false;
					}
			}catch (Exception e) {
				logger.error("=============save the file error=========:"+e.getMessage());
			}
		}
		return flag;
	}
	public void saveFiles() {
		//若没有上传文件，则返回
		if(fileSet.size()==0) return;
		
		if(fileSet.size()>0){
			fileNames=new String[fileSet.size()];
			filePaths=new String[fileSet.size()];	
			fileFormName=new String[fileSet.size()];			
		}

		String relatedPath=getFileDirectoryPath();
		//取得要保存的目录
		String serverPath=request.getSession().getServletContext().getRealPath("/")
			+relatedPath;
		
		File dirFile=new File(serverPath);
		if(!dirFile.exists()){
			dirFile.mkdirs();
		}
		
		logger.info("File directory path is :"+serverPath);
		
		int i=0;
		InputStream is=null;
		
		for(String fileKey:fileSet.keySet()){
			MultipartFile file = fileSet.get(fileKey);
			String fileName=file.getOriginalFilename();
			fileFormName[i]=fileKey;
			fileNames[i]=fileName;
			try{
				is = file.getInputStream();
				String ofname=file.getOriginalFilename();
				int index=ofname.lastIndexOf(".");
				if(index!=-1){
					//取得该文件的原扩展名称
					ofname= ofname.substring(index);
					if(fileType!=5){
						//生成随机的数据文件名称
				        ofname=getGenernateFileName()+ofname;
					}else{
						ofname=fileName;
					}
			        //保存文件路径
			        filePaths[i]=relatedPath+"/"+ofname;
			        filePathMap.put(fileKey, relatedPath+"/"+ofname);
			        
						String ext= fileName.substring(index+1);
						if(fileExtAllowed.indexOf(ext.toLowerCase())==-1){
							writeOtherFile(file, serverPath+"/"+ofname);
						}else{
					        //写文件
					        writeFile(file, serverPath+"/"+ofname);
						}
				}
			}catch (Exception e) {
				logger.error("=============save the file error=========:"+e.getMessage());
			}
			i++;
		}
		
	}

	public boolean isExit(){
		String relatedPath=getFileDirectoryPath();
		//取得要保存的目录
		String serverPath=request.getSession().getServletContext().getRealPath("/")
			+relatedPath;
		
		int i=0;
		boolean flag=false;
		for(String fileKey:fileSet.keySet()){
			MultipartFile file = fileSet.get(fileKey);
			String fileName=file.getOriginalFilename();
			File dirFile=new File(serverPath+"/"+fileName);
			if(dirFile.exists()){
				flag=true;
				break;
			}
		}
	
		return flag;
	}
	public boolean validate() {
		if(!ALLOWED_FILE_EXT_ALL.equals(fileExtAllowed)){
			for(MultipartFile file:fileSet.values()){
				if(file.getSize()>MAX_FILE_SIZE){
					return false;
				}
				String fileName=file.getOriginalFilename();
				int index=fileName.indexOf(".");
				if(index!=-1){
					String ext= fileName.substring(index+1);
					if(fileExtAllowed.indexOf(ext.toLowerCase())==-1){
						return false;
					}
				}
			}
		}
		return true;
	}
	
	private void writeOtherFile(MultipartFile file,String absFilePath) throws IOException{
			
	        InputStream is=null;
	        DataOutputStream out=null;
	        try {
	        	out= new DataOutputStream(new FileOutputStream(absFilePath));
	        	is = file.getInputStream();
				byte[] buffer = new byte[1024];
				while (is.read(buffer) > 0) {
					out.write(buffer);// 写入磁盘；
				}
				
			} catch (IOException ex) {
				ex.printStackTrace();
			} finally {
				if (is != null) {
					is.close();
				}
				if (out != null) {
					out.close();
				}
			}
	}
	
	private void writeFile(MultipartFile file,String absFilePath) throws IOException{
		
        InputStream is=null;
        DataOutputStream out=null;
        try {
        	out= new DataOutputStream(new FileOutputStream(absFilePath));
        	is = file.getInputStream();
			byte[] buffer = new byte[1024];
			while (is.read(buffer) > 0) {
				out.write(buffer);// 写入磁盘；
			}
			
			//若为产品的图片，同时产生中小图片
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (is != null) {
				is.close();
			}
			if (out != null) {
				out.close();
			}
		}
			
		/*if(FILE_TYPE_IMAGE_Ad_IMAGE.equals(fileType)){//若为广告图片，需要同时生成缩略图
			String smallPath=absFilePath.replace(FileUpload.IMG_SUFFIX_ORG, FileUpload.IMG_SUFFIX_SMALL);
			ImageThumail.createThumbnail(absFilePath, smallPath, ConfigUtil.getInstance().getSmallImageMaxDim(FileUpload.PRODUCT_SMALL_MESSAGE));
		}else if(FILE_TYPE_IMAGE_PRODUCT.equals(fileType)){//若为产品图片，需要同时生成原大图+大号缩略图+小号缩略图
			String smallPath=absFilePath.replace(FileUpload.IMG_SUFFIX_ORG, FileUpload.IMG_SUFFIX_SMALL);
			String midPath=absFilePath.replace(FileUpload.IMG_SUFFIX_ORG, FileUpload.IMG_SUFFIX_MID);
			
			ImageThumail.createThumbnail(absFilePath, smallPath, ConfigUtil.getInstance().getSmallImageMaxDim(FileUpload.PRODUCT_SMALL_MESSAGE));
			ImageThumail.createThumbnail(absFilePath, midPath, ConfigUtil.getInstance().getXorgImageMaxDim(FileUpload.PRODUCT_XORG_MESSAGE));
		}else if(FILE_ACTIVITY_WORK.equals(fileType)){//若为超级买手、超级设计作品，需要同时生成原大图+大号缩略图+小号缩略图
			String smallPath=absFilePath.replace(FileUpload.IMG_SUFFIX_ORG, FileUpload.IMG_SUFFIX_SMALL);
			String midPath=absFilePath.replace(FileUpload.IMG_SUFFIX_ORG, FileUpload.IMG_SUFFIX_MID);
			
			ImageThumail.createThumbnail(absFilePath, smallPath, ConfigUtil.getInstance().getSmallImageMaxDim(FileUpload.ACTIVITY_WORK_SMALL_MESSAGE));
			ImageThumail.createThumbnail(absFilePath, midPath, ConfigUtil.getInstance().getXorgImageMaxDim(FileUpload.ACTIVITY_WORK_XORG_MESSAGE));
		}else if(FILE_TYPE_IMAGE_PHOTO_ALBUM.equals(fileType)){//若为相册图片，需要同时生成原大图+大号缩略图+小号缩略图
			String smallPath=absFilePath.replace(FileUpload.IMG_SUFFIX_ORG, FileUpload.IMG_SUFFIX_SMALL);
			
			ImageThumail.createThumbnail(absFilePath, smallPath, ConfigUtil.getInstance().getSmallImageMaxDim(FileUpload.ALBUM_SMALL));
		}else if(FILE_ACTIVITY_AWARDS.equals(fileType)){//若为活动宣传（获奖）图片，需要同时生成缩略图
			String smallPath=absFilePath.replace(FileUpload.IMG_SUFFIX_ORG, FileUpload.IMG_SUFFIX_SMALL);
			
			ImageThumail.createThumbnail(absFilePath, smallPath, ConfigUtil.getInstance().getSmallImageMaxDim(FileUpload.ACTIVITY_AWARD_XORG_MESSAGE));
		}else if(FILE_TYPE_IMAGE_ACTIVITY_THEME.equals(fileType)){//若为活动主题海报图片，需要同时缩略图
			String smallPath=absFilePath.replace(FileUpload.IMG_SUFFIX_ORG, FileUpload.IMG_SUFFIX_SMALL);
			
			ImageThumail.createThumbnail(absFilePath, smallPath, ConfigUtil.getInstance().getSmallImageMaxDim(FileUpload.ACTIVITY_POSTERS_SMALL_MESSAGE));
		}else if(FILE_TYPE_HOME_IMAGE.equals(fileType)){
			String smallPath=absFilePath.replace(FileUpload.IMG_SUFFIX_ORG, FileUpload.IMG_SUFFIX_SMALL);
			ImageThumail.createThumbnail(absFilePath, smallPath, ConfigUtil.getInstance().getSmallImageMaxDim(FileUpload.HOME_XSMALL_IAMGE));
		}else if(FILE_TYPE_ACTIVITY.equals(fileType)){//若为活动 小组 生成小图和中图
			String smallPath=absFilePath.replace(FileUpload.IMG_SUFFIX_ORG, FileUpload.IMG_SUFFIX_SMALL);
			String midPath=absFilePath.replace(FileUpload.IMG_SUFFIX_ORG, FileUpload.IMG_SUFFIX_MID);
			
			ImageThumail.createThumbnail(absFilePath, smallPath, ConfigUtil.getInstance().getSmallImageMaxDim(FileUpload.GROUP_XSMALL_MESSAGE));
			ImageThumail.createThumbnail(absFilePath, midPath, ConfigUtil.getInstance().getXorgImageMaxDim(FileUpload.GROUP_XMID_MESSAGE));
		}*/
	}

	public String[] getFileNames() {
		return fileNames;
	}

	public String[] getFilePaths() {
		return filePaths;
	}

	public String[] getFileFormName() {
		return fileFormName;
	}

	public Set<MultipartFile> getFileSet() {
		return new HashSet<MultipartFile>(fileSet.values());
	}

	public boolean haveNewUploadFile() {
		return fileSet.size() != 0;
	}

	public HashMap<String, String> getFilePathMap() {
		return filePathMap;
	}

	public void setFilePathMap(HashMap<String, String> filePathMap) {
		this.filePathMap = filePathMap;
	}
	
}
